package org.tigris.atlas.web.struts;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.tigris.atlas.messages.DefaultMessages;
import org.tigris.atlas.messages.Message;
import org.tigris.atlas.messages.MessageUtils;
import org.tigris.atlas.messages.Messages;

/**
 * Base class for input forms.
 * 
 * @author sandrews
 *
 */
public abstract class InputForm extends ActionForm  {
	
	private Messages messages;
	
	/**
	 * All subclasses are responsible for validating themselves.
	 */
	public abstract void validate(HttpServletRequest request);
		
	/**
	 * @deprecated - Use validate(HttpServletRequest) to validate
	 */
	public final ActionErrors validate(ActionMapping arg0, HttpServletRequest arg1) {
		throw new UnsupportedOperationException("Use validate(HttpServletRequest) to perform validations");
	}

	/**
	 * @deprecated - Use validate(HttpServletRequest) to validate
	 */
	public final ActionErrors validate(ActionMapping arg0, ServletRequest arg1) {
		throw new UnsupportedOperationException("Use validate(HttpServletRequest) to perform validations");
	}

	public void reset(ActionMapping mapping, HttpServletRequest request) {
		super.reset(mapping, request);
		
		messages = createMessages();
		
		doReset(mapping, request);
	}
	
	protected abstract void doReset(ActionMapping mapping, HttpServletRequest request);

	public final Messages getMessages() {
		if (messages == null) {
			messages = createMessages();
		}
		return messages;
	}
	
	protected Messages createMessages() {
		return new DefaultMessages();
	}
	
	public final void addMessages(Messages msgs,  HttpServletRequest request) {
		getMessages().addMessages(msgs);
		setFieldLevelErrorMessages(getMessages(), request);
	}

	protected abstract void setFieldLevelErrorMessages(Messages messages, HttpServletRequest request);

	protected String getFieldLevelMessage(Message message, HttpServletRequest request) {
		String msg = MessageUtils.getDetailMessage(message.getKey(), message.getInserts(), getClass(), request.getLocale());
		return msg;
	}
	
}
